package com.yangjunli.bishe.utils;

import com.google.common.base.Strings;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;

public class tokenUtils {

    private static final String BASE64_SECURITY = "1234567879";

    /**
     * 解析JWT
     * @param jsonWebToken
     * @param base64Security
     * @return
     */
    public static Claims parseJWT(String jsonWebToken, String base64Security) {
        try {
            if(Strings.isNullOrEmpty(base64Security)){
                base64Security = BASE64_SECURITY;
            }
            Claims claims = Jwts.parser()
                    .setSigningKey(DatatypeConverter.parseBase64Binary(base64Security))
                    .parseClaimsJws(jsonWebToken).getBody();
            return claims;
        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * 创建JWT
     * @param no
     * @param userId
     * @param issuer
     * @param TTLMillis
     * @param base64Security
     * @return
     */
    public static String createJWT(String no, String userId,
                                   String issuer, long TTLMillis, String base64Security) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        //生成签名密钥
        if(Strings.isNullOrEmpty(base64Security)){
            base64Security = BASE64_SECURITY;
        }
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Security);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
        //添加构成JWT的参数
        JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
                .claim("no", no)
                .setSubject(userId)
                .setIssuer(issuer)
                .signWith(signatureAlgorithm, signingKey);
        //添加Token过期时间
        if (TTLMillis >= 0) {
            long expMillis = nowMillis + TTLMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp).setNotBefore(now);
        }
        //生成JWT
        return builder.compact();
    }


    public static void main(String[] args) {
        String  token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJubyI6IjEiLCJzdWIiOiI3IiwiaXNzIjoic3lzdGVtIiwiZXhwIjoxNTg2MTU0NTAxLCJuYmYiOjE1ODYxNDQ1MDF9.UrVoWiCzZxkF9JqmclKXX4yLQNESuE0pAyI0Gx_vz0s";
        Claims claims = parseJWT(token,"");
        System.out.println(claims.toString());
    }
}
